package 作业1;

import java.awt.*;

import java.awt.event.*;

public class Target implements Runnable {

    StringBuffer buffer=new StringBuffer();

    Thread cat,dog,mouse;

    Target() {  cat=new Thread(this);

        dog=new Thread(this);

        mouse=new Thread(this);

    }



    public synchronized void addChar(char c) {

        if(Thread.currentThread()==cat) {

            while(buffer.length()==0) {

                try{ wait();

                    System.out.println("cat");

                }            catch(Exception e){}          }

            buffer.append(c);

            notifyAll();      }



        if(Thread.currentThread()==dog) {

            while(buffer.length()==0||buffer.length()==1) {

                try{ wait();

                    System.out.println("dog");

                }            catch(Exception e){}

            }

            buffer.append(c);     }

        if(Thread.currentThread()==mouse) {

            buffer.append(c);

            notifyAll();     }  }

    public void run() {

        if(Thread.currentThread()==cat)

            addChar('1') ;

        if(Thread.currentThread()==dog)

            addChar('2') ;

        if(Thread.currentThread()==mouse)

            addChar('3') ;  }

    public static void main(String s[]) {

        Target target=new Target();

        target.cat.start();

        target.dog.start();

        target.mouse.start();

        while(target.cat.isAlive()||target.dog.isAlive()|target.mouse.isAlive()){}

        System.out.println(target.buffer);    //【代码】

    } }
